package com.kevin.nettyrpcconsumer.proxy;

import com.alibaba.fastjson.JSON;
import com.kevin.nettyrpcapi.common.RpcRequest;
import com.kevin.nettyrpcapi.common.RpcResponse;
import com.kevin.nettyrpcconsumer.client.RpcClient;
import io.netty.handler.codec.json.JsonObjectDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * @Author LXL
 * @Date 2021/9/28 10:58
 **/
public class RpcClientProxy {

    public static Object createProxy(Class serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.封装Rpcclient对象
                        RpcClient rpcClient = new RpcClient("127.0.0.1", 8889);
                        try {

                            //3.发送消息
                            Object responseMsg = rpcClient.sendMsg(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if(rpcResponse.getError() != null){
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        }catch (Exception e){
                            throw e;
                        }finally {
                            rpcClient.close();
                        }
                    }
                });
    }
}
